package cn.aishu.anydream.service;

import cn.aishu.anydream.dao.UserMapper;
import cn.aishu.anydream.entity.User;
import cn.aishu.common.AishuException;
import cn.aishu.common.ResponseModel;
import cn.aishu.common.ToolBox;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin(origins = "${aishu.web.path}", allowedHeaders = "*", allowCredentials = "true")
@RestController
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserMapper userMapper;

    @Override
    @PostMapping("/users/login")
    public ResponseModel login(String userName, String passWord) {

        // 检查参数
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(passWord)) {
            throw new AishuException("参数不合法！");
        }

        // 加密密码
        String encryptedPwd = ToolBox.md5(passWord);

        // 查找数据库
        User user = userMapper.selectByUserName(userName);

        // 校验用户
        if (user == null) {
            // 没有查找到该用户
            throw new AishuException("用户不存在！");
        }

        // 校验密码
        if (!StringUtils.equals(encryptedPwd, user.getPassword())) {
            throw new AishuException("密码错误！");
        }

        // 封装返回
        String message = "登录成功！";
        return new ResponseModel(message);
    }
}
